<template>
  <TaskChatDialog
    v-model="visible"
    :title="title"
    width="40%"
    @close="close"
    :close-on-click-modal="false"
    destroy-on-close>
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="120px">
      <el-form-item label="分组名称：" prop="itemName">
        <el-input v-model.trim="form.itemName" maxlength="18" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="计划时间：" prop="itemBegin">
        <!--           :default-time="defaultTime" -->
        <el-date-picker
          :model-value="[form.itemBegin, form.itemEnd]"
          type="daterange"
          format="YYYY-MM-DD"
          range-separator="-"
          clearable
          :unlink-panels="true"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-time="defaultTime"
          :disabled-date="
            (date) =>
              dayjs(projectStore.getProjectInfo.planBegin).isAfter(date, 'day') ||
              dayjs(projectStore.getProjectInfo.planEnd).isBefore(date, 'day')
          "
          @update:model-value="planDateChange" />
      </el-form-item>
      <el-form-item label="父级节点：" prop="itemId">
        <el-select v-model="form.parentId" placeholder="请选择" clearable>
          <el-option
            v-for="(item, index) in treeData"
            :key="index"
            :label="item.itemName"
            :value="item.itemId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="阶段分管：" prop="itemManager">
        <el-select v-model="form.itemManager" clearable placeholder="请选择" filterable>
          <el-option v-for="item in projectMemberList" :key="item.value" :label="item.userName" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="颜色设置：" prop="itemColor">
        <el-color-picker v-model="form.itemColor" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="onSubmit" :loading="isLoading">提交</el-button>
      <el-button @click="close">取消</el-button>
    </template>
  </TaskChatDialog>
</template>

<script setup>
import { getProjectMember, getRootItemList } from '@/assets/api/project'
import { addTcTaskItem, editTcTaskItem, getTaskItemsDetail } from '@/assets/api/task'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import useProject from '@/store/project'

const projectStore = useProject()

const emit = defineEmits(['refresh'])

defineExpose({
  open,
})

const projectId = ref()
const taskGroupId = ref()
const isLoading = ref(false)
const visible = ref(false)

const title = computed(() => {
  return form.value.itemId ? '修改阶段' : '添加阶段'
})

const defaultTime = reactive([new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)])

// 表单配置
const formRef = ref()

const form = ref({})

const formRules = {
  itemName: [{ required: true, message: '请输入', trigger: 'blur' }],
  itemBegin: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!form.value.itemBegin || !form.value.itemEnd) {
          callback(new Error('计划时间不可为空'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
  ],
  projectId: [{ required: true, message: '请选择', trigger: 'change' }],
}

// 获取详情
async function getTaskItemsDetailData(itemId) {
  getTaskItemsDetail(itemId).then((res) => {
    if (res.code === 200) {
      form.value = res.data
      form.value.parentId = form.value.parentId ? form.value.parentId : ''
      myWatch(form.value)
    } else {
      ElMessage.error(res.msg)
    }
  })
}

function planDateChange(date) {
  form.value.itemBegin = date && date.length > 1 ? dayjs(date[0]).valueOf() : ''
  form.value.itemEnd = date && date.length > 1 ? dayjs(date[1]).valueOf() : ''
}

const projectMemberList = ref([])

function getProjectMemberData() {
  getProjectMember({ projectId: projectId.value, effectFlag: 1 }).then((res) => {
    if (res.code === 200) {
      projectMemberList.value = res.rows
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const treeData = ref([])

function getRootItemListData() {
  getRootItemList({ projectId: projectId.value }).then((res) => {
    if (res.code === 200) {
      treeData.value = res.rows || []
      treeData.value = treeData.value.filter((item) => item.itemId !== taskGroupId.value)
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 提交
async function onSubmit() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const isAdd = !form.value.itemId
      // const data = JSON.parse(JSON.stringify(form.value))
      const data = Object.assign(JSON.parse(JSON.stringify(form.value)), emptyData)
      if (isAdd) {
        data.projectId = projectId.value
      }
      if (!data.itemManager) {
        data.itemManager = -1
      }
      isLoading.value = true
      const res = await (isAdd ? addTcTaskItem : editTcTaskItem)(data)
      if (res.code === 200) {
        ElMessage.success('提交成功')
        close()
        emit('refresh')
      } else {
        ElMessage.error(res.msg)
      }
      isLoading.value = false
    }
  })
}

const emptyData = {}

function myWatch(obj) {
  Object.keys(obj).forEach((item) => {
    const refValue = toRefs(obj)[item]
    watch(
      () => refValue.value,
      (newVal, oldVal) => {
        if (item !== 'parentId') {
          if (!newVal) {
            emptyData[item] = -1
          } else if (emptyData[item]) {
            delete emptyData[item]
          }
        }
      }
    )
  })
}

function open(itemId, pid) {
  if (itemId) {
    taskGroupId.value = itemId
    getTaskItemsDetailData(itemId)
  }
  projectId.value = pid
  getProjectMemberData()
  getRootItemListData()
  visible.value = true
}

// 关闭对话框
function close() {
  form.value = {}
  projectId.value = ''
  taskGroupId.value = ''
  visible.value = false
}
</script>

<style lang="scss" scoped>
.elp-input,
.elp-select {
  width: 100%;
}
</style>
